package com.wen.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.wen.apicommon.model.entity.InterfaceInfo;
import com.wen.apicommon.model.entity.UserInterfaceInfo;
import com.wen.project.annotation.AuthCheck;
import com.wen.project.common.BaseResponse;
import com.wen.project.common.ErrorCode;
import com.wen.project.common.ResultUtils;
import com.wen.project.exception.BusinessException;
import com.wen.project.mapper.UserInterfaceInfoMapper;
import com.wen.project.model.vo.InterfaceInfoVo;
import com.wen.project.service.InterfaceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分析控制器
 */
@RestController
@RequestMapping("/analysis")
@Slf4j
public class AnalysisController {
    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @GetMapping("/top/interface/invoke")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<List<InterfaceInfoVo>> getTopInvokeInterfaceInfo() {

        List<UserInterfaceInfo> userInterfaceInfoList = userInterfaceInfoMapper.getTopInvokeInterfaceInfo(3);
        //获取list 中的聚合拿到的 UserInterfaceInfo 对象的Map key:interfaceInfoId value:List<UserInterfaceInfo>
        Map<Long, List<UserInterfaceInfo>> interfaceInfoObjMap = userInterfaceInfoList.stream().collect(Collectors.groupingBy(UserInterfaceInfo::getInterfaceInfoId));
        //根据 interfaceInfoId 获取 InterfaceInfo 对象集合
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",interfaceInfoObjMap.keySet());
        List<InterfaceInfo> list = interfaceInfoService.list(queryWrapper);
        if(CollectionUtils.isEmpty(list)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        //通过 interfaceInfoId 获取对应的 UserInterfaceInfo 对象的 totalNum 值，然后封装 VO 集合
        List<InterfaceInfoVo> interfaceInfoVoList = list.stream().map(interfaceInfo -> {
            InterfaceInfoVo interfaceInfoVo = new InterfaceInfoVo();
            BeanUtils.copyProperties(interfaceInfo, interfaceInfoVo);
            int totalNum = interfaceInfoObjMap.get(interfaceInfo.getId()).get(0).getTotalNum();
            interfaceInfoVo.setTotalNum(totalNum);
            return interfaceInfoVo;
        }).collect(Collectors.toList());
        return ResultUtils.success(interfaceInfoVoList);
    }
}
